import sys
from paste.request import parse_formvars
from paste.response import HeaderDict

class Request(object):
    def __init__(self, environ):
        """docstring for __init__"""
        self.environ = environ
        self.fields = parse_formvars(environ)

class Response(object):
    def __init__(self):
        """docstring for __init__"""
        self.headers = HeaderDict(
                {'content-type': 'text/html'})

class ObjectPublisher(object):

    def __init__(self, root):
        """docstring for __init__"""
        self.root = root

    def __call__(self, environ, start_response):
        """docstring for __call__"""
        request = Request(environ)
        response = Response()
        obj = self.find_obj(self.root, environ)
        response_body = obj(**dict(request.fields))
        start_response('200 OK', response.headers.items())
        return [response_body]

    def find_obj(self, obj, environ):
        path_info = environ.get('PATH_INFO', '')
        if not path_info or path_info == '/':
            return obj
        path_info = path_info.lstrip('/')
        parts = path_info.split('/', 1)
        next = parts[0]
        if len(parts) == 1:
            rest = ''
        else:
            rest = '/' + parts[1]

        assert not next.startswith('_')
        next_obj = getattr(obj, next)
        environ['SCRIPT_NAME'] += '/' + next
        environ['PATH_INFO'] = rest
        return self.find_obj(next_obj, environ)

class demoapp(object):
    def __call__(self):
        """docstring for __call"""
        return '''
        <form action="welcome">
        Name: <input type="text" name="name">
        <input type="submit">
        </form>
        '''

    def welcome(self, name):
        return 'Hello %s!' % name

if __name__ == '__main__':
    app = ObjectPublisher(demoapp())
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8080')

